package com.dianpingmedia.simulate;

import com.alibaba.fastjson.JSON;
import com.dianpingmedia.common.utils.GsonUtil;
import com.dianpingmedia.common.utils.MiscUtil;
import com.dianpingmedia.proto.ProtoZmeng;
import com.dianpingmedia.simulate.model.ZmAdJsonRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.protobuf.ByteString;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.dianpingmedia.proto.ProtoZmeng.Device.DeviceType.OUTDOOR_SCREEN;
import static com.dianpingmedia.proto.ProtoZmeng.Device.OsType.ANDROID;

public class Test {

    private static ProtoZmeng.ZmAdRequest simulateRequest;

    static {

        ProtoZmeng.Version version = ProtoZmeng.Version.newBuilder()
                .setMajor(5)
                .setMinor(1)
                .setMicro(1)
                .build();

        ProtoZmeng.Size screenSize = ProtoZmeng.Size.newBuilder()
                .setHeight(1920)
                .setWidth(1080)
                .build();

        ProtoZmeng.UdId udId = ProtoZmeng.UdId.newBuilder()
                .setAndroidId("KJd06f4a6288c4")
                .setImei("-1-113061541062")
                .setMac("D0:6F:4A:5F:E5:69")
                .build();

        ProtoZmeng.Size adSlotsize = ProtoZmeng.Size.newBuilder()
                .setWidth(1920)
                .setHeight(1080)
                .build();

        ProtoZmeng.Device device = ProtoZmeng.Device.newBuilder()
                .setDeviceType(OUTDOOR_SCREEN)
                .setOsType(ANDROID)
                .setOsVersion(version)
                .setModel(ByteString.copyFrom("Android".getBytes()))
                .setVendor(ByteString.copyFrom("XBHAndroid".getBytes()))
                .setUdid(udId)
                .setScreenSize(screenSize)
                .build();

        ProtoZmeng.Network.ConnectionType connectionType = ProtoZmeng.Network.ConnectionType.valueOf(0);
        ProtoZmeng.Network.OperatorType operatorType = ProtoZmeng.Network.OperatorType.valueOf(0);
        ProtoZmeng.Network network = ProtoZmeng.Network.newBuilder()
                .setIpv4("192.168.1.100")
                .setConnectionType(connectionType)
                .setOperatorType(operatorType)
                .setCellularId("")
                .build();

        ProtoZmeng.AdSlot adSlot = ProtoZmeng.AdSlot.newBuilder()
                .setDuration(60)
                .setType(0)
                .setAdslotSize(adSlotsize)
                .build();


        simulateRequest = ProtoZmeng.ZmAdRequest.newBuilder()
                .setChannelId("test")
                .setScreenId("131000001")
                .setRequestId(getRequestId())
                .setDevice(device)
                .setAdslot(adSlot)
                .setNetwork(network)
                .setToken("uihoaasjhfqnajufqnmasofwsdsadasd")
                .build();

    }


    private static void getZmAd(byte[] bytes) {

        URL url = null;
        try {
            url = new URL("http://localhost:8026/zmt/api/ad/getAd.do");
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setConnectTimeout(5 * 1000);
            urlConn.setReadTimeout(5 * 1000);
            urlConn.setDoOutput(true);
            urlConn.setDoInput(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestMethod("POST");
            urlConn.setInstanceFollowRedirects(true);
            urlConn.setRequestProperty("Content-Type", "application/x-protobuf");
            urlConn.setRequestProperty("Charset", "UTF-8");
            urlConn.connect();
            DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
            dos.write(bytes);
            dos.flush();
            dos.close();
            System.out.println("urlConn.getResponseCode()=" + urlConn.getResponseCode());
            if (urlConn.getResponseCode() == 200 || urlConn.getResponseCode() == 204) {
                byte[] re = inputStreamTOByte(urlConn.getInputStream());
                try {
                    final ProtoZmeng.ZmAdResponse zmAdResponse = ProtoZmeng.ZmAdResponse.parseFrom(re);
                    if (zmAdResponse == null || zmAdResponse.toString() == null || zmAdResponse.toString().equals("")) {
                    } else {
                        System.out.println(zmAdResponse.toString());
                    }
                } catch (IOException e) {
                }
            } else {

            }
            urlConn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static String getRequestId() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String requestId = uuid;
        String strRand = "";
        try {
            for (int i = 0; i < 32 - requestId.length(); i++) {
                strRand += String.valueOf((int) (Math.random() * 10));
            }
        } catch (Exception e) {
            System.out.println("getRequestId e =" + e);
        }
        return requestId + strRand;
    }


    private static byte[] inputStreamTOByte(InputStream in) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int count = -1;
        while ((count = in.read(data, 0, 1024)) != -1) {
            outStream.write(data, 0, count);
        }
        return outStream.toByteArray();
    }


    public static class Test2 {
        public Double a;

        public Test2(Double a) {
            this.a = a;
        }
    }


    public static void main(String[] args) {
//        getZmAd(simulateRequest.toByteArray());
        Test2 test2 = new Test2(100.00d);
        Map<String,Object> map = GsonUtil.fromJson(MiscUtil.gson.toJson(test2), new TypeToken<Map<String, Object>>() {
        });

        System.out.println(map.values().toArray()[0].getClass());



        Map<String,Map<String,String>> a=new HashMap<>();
        HashMap<String, String> value = new HashMap<>();
        a.put("100", value);
        value.put("1111","22222");
        value.put("1112","222222");

        String s = JSON.toJSONString(a);

        System.out.println(s);


        String sssssss = MiscUtil.MD5("sssssss").substring(0, 8);
        System.out.println(sssssss);
    }


}
